# coding=utf-8
import json
from abc import ABCMeta

import tornado.web

import WrapCursor
from CommonLib import CheckJsonKeys, CheckAuth
from database.models.DatabaseCommon import *
from database.models.PanelInstruct import PanelInstruct


class DelPanelNormal(tornado.web.RequestHandler):
    __metaclass__ = ABCMeta

    def post(self):
        ojson = None
        r = WrapCursor.WrapCursor()
        try:
            ojson = json.loads(self.request.body)
            CheckJsonKeys(ojson, 'ControllerID', 'key')
            CheckJsonKeys(ojson, 'username', 'userpass')
            CheckAuth(ojson)
        except Exception as e:
            self.write(r.Error(u'请求数据错误 :' + str(e.message)))
            return
        cid = ojson['ControllerID']
        key = ojson['key']

        s = Session()

        ps = s.query(PanelInstruct).filter_by(ControllerID=cid, Key=key).all()
        if ps is not None:
            if len(ps) >= 1:
                for i in ps:
                    s.delete(i)
            else:
                self.write(r.Error(u'失败：所要删除的动作不存在'))
                return
        try:
            s.commit()
        except Exception as e:
            self.write(r.Error(u'失败:删除面板动作失败'))
            return
        self.write(r.Ok(u'成功'))
        return
